from simpy import Resource, Environment

from x_pc.core import Device, DeviceCost, System
from x_pc.model.model import Task


class CM(Device, DeviceCost):
    """
    301 栈板拆模区
    拆膜(CM)
    """
    # 拆膜耗时
    COST = 5

    resource: Resource = None

    def __init__(self, env: Environment, name: str):
        super().__init__(env, name)
        self.resource = Resource(env)

    def cost(self, *args, **kwargs) -> float:
        return self.COST


class CMSystem(System):
    """
    栈板拆膜区 系统
    """
    cm_list: list[CM] = []

    def __init__(self, env: Environment, name: str):
        super().__init__(env, name)
        self.__init_cm_list()

    def __init_cm_list(self):
        self.cm_list = [CM(self.env, '拆模区')]

    def run_task(self, task: Task):
        if not self.cm_list:
            while self.running:
                yield self.env.timeout(1)
                if self.cm_list:
                    break
        # 取用资源
        cm = self.cm_list.pop(0)
        with cm.resource.request() as req:
            yield req
            #
            yield self.env.timeout(cm.cost())
        # 归还资源
        self.cm_list.append(cm)
